package com.yudaob2b.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;

public class HttpUtils {
    final static Logger log = LoggerFactory.getLogger(HttpUtils.class);

    public static String postBody(String url, String data) {
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        try {
            // Post请求
            HttpPost httppost = new HttpPost(url);

            EntityBuilder entity1 = EntityBuilder.create();
            entity1.setContentType(ContentType.APPLICATION_XML);// 很重要，设置请求类型为
            // application/xml
            entity1.setText(data);// 设置请求内容到http body中
            // 设置参数
            httppost.setEntity(entity1.build());
            // 发送请求
            HttpResponse httpresponse = closeableHttpClient.execute(httppost);
            int status = httpresponse.getStatusLine().getStatusCode();
            // 判断http状态是否为200
            if (HttpStatus.SC_OK == status) {
                // 获取返回数据
                HttpEntity entity = httpresponse.getEntity();
                String body = EntityUtils.toString(entity, "UTF-8");
                return body;
            } else {
                //log.info("==========处理失败=======http status=" + status);
            }
        } catch (Exception e) {
            log.error("调用http接口异常：" + e.getMessage(), e);
        } finally {
            try {
                closeableHttpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    /**
     * HTTP Post 获取内容
     *
     * @param url     请求的url地址 ?之前的地址
     * @param params  请求的参数
     * @param charset 编码格式
     * @return 页面内容
     */
    public static String post(String url, Map<String, String> params, String charset) {
        if (StringUtils.isBlank(url)) {
            return null;
        }

        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();

        try {
            List<NameValuePair> pairs = null;
            if (params != null && !params.isEmpty()) {
                pairs = new ArrayList<NameValuePair>(params.size());
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    String value = entry.getValue();
                    if (value != null) {
                        pairs.add(new BasicNameValuePair(entry.getKey(), value));
                    }
                }
            }
            HttpPost httpPost = new HttpPost(url);
            if (pairs != null && pairs.size() > 0) {
                httpPost.setEntity(new UrlEncodedFormEntity(pairs, charset));
            }
            HttpResponse response = closeableHttpClient.execute(httpPost);

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                httpPost.abort();
                log.error("发送http请求异常：url=" + url + "，params=" + params + "，statusCode=" + statusCode);
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, "utf-8");
            }
            EntityUtils.consume(entity);
            return result;
        } catch (Exception e) {
            log.error("发送http请求异常：url=" + url + "，params=" + params + "，" + e.getMessage(), e);
        } finally {
            try {
                closeableHttpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String post(String url, String params, String methodType, String encoding, String contentType) {
        System.setProperty("jsse.enableSNIExtension", "false");
        if (StringUtils.isEmpty(encoding)) {
            encoding = "UTF-8";
        }
        if (StringUtils.isEmpty(methodType)) {
            methodType = "GET";
        }
        if (StringUtils.isEmpty(contentType)) {
            contentType = "application/x-www-form-urlencoded";
        }

        URL u = null;
        HttpURLConnection con = null;
        StringBuffer content = new StringBuffer();
        // 发送请求
        try {
            u = new URL(url);
            con = (HttpURLConnection) u.openConnection();
            con.setRequestMethod(methodType.toUpperCase());
            con.setRequestProperty("Content-Type", contentType);
            // con.setRequestProperty("Content-Type","application/json");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            // 构建请求参数
            if (methodType.equalsIgnoreCase("post")) {
                OutputStreamWriter osw = new OutputStreamWriter(
                        con.getOutputStream(), encoding);
                osw.write(params);
                osw.flush();
                osw.close();
            }

            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), encoding));
            String line = "";
            while ((line = br.readLine()) != null) {
                content.append(line);
            }
            br.close();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }
        return content.toString();
    }

    public static String get(String url, boolean ssl) {
        CloseableHttpClient closeableHttpClient = null;
        if (ssl) {
            closeableHttpClient = createSSLClient();
        } else {
            closeableHttpClient = HttpClients.createDefault();
        }
        try {
            // get请求
            HttpGet get = new HttpGet(url);
            // 发送请求
            HttpResponse httpresponse = closeableHttpClient.execute(get);
            int status = httpresponse.getStatusLine().getStatusCode();
            // 判断http状态是否为200
            if (HttpStatus.SC_OK == status) {
                // 获取返回数据
                HttpEntity entity = httpresponse.getEntity();
                String body = EntityUtils.toString(entity, "UTF-8");
                EntityUtils.consume(entity);
                return body;
            } else {
                //log.info("==========处理失败=======http status=" + status);
            }
        } catch (Exception e) {
            log.error("调用http接口异常 url:{}, errorMsg:{}" ,url , e.getMessage(), e);
        } finally {
            try {
                closeableHttpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 请求验证接口
     *
     * @param url        访问地址
     * @param apiRequest 是否以api方式访问
     * @return
     */
    public static String getPersonCheck(String url, boolean apiRequest) {
        CloseableHttpClient closeableHttpClient = createSSLClient();
        try {
            // get请求
            HttpGet get = new HttpGet(url);
            if (apiRequest) {
                get.addHeader("X-Requested-With", "OpenAPIRequest");
            }
            // 发送请求
            HttpResponse httpresponse = closeableHttpClient.execute(get);
            int status = httpresponse.getStatusLine().getStatusCode();
            // 判断http状态是否为200
            if (HttpStatus.SC_OK == status) {
                // 获取返回数据
                HttpEntity entity = httpresponse.getEntity();
                String body = EntityUtils.toString(entity, "UTF-8");
                EntityUtils.consume(entity);
                return body;
            } else {
                //log.info("==========处理失败=======http status=" + status);
            }
        } catch (Exception e) {
            log.error("调用http接口异常：" + e.getMessage(), e);
        } finally {
            try {
                closeableHttpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * HTTP Get 获取内容
     *
     * @param url     请求的url地址 ?之前的地址
     * @param params  请求的参数
     * @param charset 编码格式
     * @return 页面内容
     */
    public static String doGet(String url, Map<String, String> params, String charset) {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        CloseableHttpClient closeableHttpClient = createSSLClient();
        try {
            if (params != null && !params.isEmpty()) {
                List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    String value = entry.getValue();
                    if (value != null) {
                        pairs.add(new BasicNameValuePair(entry.getKey(), value));
                    }
                }
                url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
            }

            log.info("doGet url============" + url);
            HttpGet httpGet = new HttpGet(url);
            HttpResponse response = closeableHttpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpGet.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, "utf-8");
            }
            EntityUtils.consume(entity);
            return result;
        } catch (Exception e) {
            log.error("发送http请求异常：" + e.getMessage(), e);
        } finally {
            try {
                closeableHttpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static CloseableHttpClient createSSLClient() {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                //信任所有
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();

        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        return HttpClients.createDefault();
    }


    public static void main(String args[]) throws Exception {
        //for (int i = 0; i < 151; i++) {
            String url = "http://apiproxy.ctrip.com/apiproxy/soa2/11576/json/LowPricePolicyList";
            String methodType = "POST";
            String encoding = "UTF-8";
            String contentType = "application/json";

            //String param = "{\"MessageHead\":{\"UserInfo\":{\"UserName\":\"广州市纬航\",\"Password\":\"b0ed632e99e6d4751a7625a21f4f00ed\"},\"ClientID\":5,\"RequestGUID\":\"3d6447bc-9221-4753-84f1-13b30933d226\"},\"MessageBody\":{\"SearchCondition\":{\"EffectDate\":\"2016-11-26T00:00:00\",\"DepartPort\":\"BAV\",\"ArrivePort\":\"NAY\",\"TradePolicyType\":\"SPECIALPOLICY\",\"ShareProductTypeList\":[\"TravelPackage\"],\"IsRealTimeData\":\"true\"}}}";
            Map map = new HashMap();
            Map temp = new HashMap();
            temp.put("UserName", "广州市纬航");
            temp.put("Password", "b0ed632e99e6d4751a7625a21f4f00ed");

            JSONObject messageHead = new JSONObject();
            JSONObject userInfo = new JSONObject();
            userInfo.put("UserName", "广州市纬航");
            userInfo.put("Password", "b0ed632e99e6d4751a7625a21f4f00ed");

            messageHead.put("UserInfo", userInfo);
            messageHead.put("ClientID", 5);
            messageHead.put("RequestGUID", UUID.randomUUID().toString());

            List<String> shareProductTypeList = new ArrayList();
            shareProductTypeList.add("TravelPackage");

            JSONObject searchCondition = new JSONObject();
            searchCondition.put("EffectDate", "2016-11-26");
            searchCondition.put("DepartPort", "BAV");
            searchCondition.put("ArrivePort", "NAY");
            searchCondition.put("TradePolicyType", "SPECIALPOLICY");
            searchCondition.put("ShareProductTypeList", shareProductTypeList);
            //searchCondition.put("IsRealTimeData", "true");

            JSONObject messageBody = new JSONObject();
            messageBody.put("SearchCondition", searchCondition);

            JSONObject json = new JSONObject();
            json.put("MessageHead", messageHead);
            json.put("MessageBody", messageBody);

            System.out.println(json.toJSONString());


            String result = post(url, json.toJSONString(), methodType, encoding, contentType);

            System.out.println("----" + result);

            JSONObject jsonObject = JSON.parseObject(result, JSONObject.class);
            JSONObject tradeResult = JSON.parseObject(jsonObject.get("TradeResult").toString(), JSONObject.class);
            List<JSONObject> policyList = JSON.parseArray(tradeResult.get("PolicyList").toString(), JSONObject.class);
            String price = "";
            for (JSONObject obj : policyList) {
                price += obj.get("CostPrice") + "_";
            }

            System.out.println(price);
        //}
    }
}
